﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.XPath;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

namespace sodexo
{
    public class sodexoCardType
    {
        public string value;
        public string text;
        public string Text
        {
            get
            {
                return text;
            }
            set
            {
                text = value;
            }
        }
    }

    public class sodexoDistrict
    {
        public string Text
        {
            get;
            set;

        }
        public string Value
        {
            get;
            set;

        }

    }
    public class sodexoAffiliate
    {
        public string Name{get; set;}
        public string Address { get; set; }
        public string PhoneNumber { get; set; }
    }
    
    public class sodexoWebClient
    {
        private string sodexoHomeUrl;
        private string sodexoSerchHomeUrl;
        private string sodexoSerchUrl;
        private EventHandler<HtmlDocumentLoadCompleted> HomePageLoaded;
        private EventHandler<HtmlDocumentLoadCompleted> SearchPageLoaded;
        private List<sodexoCardType> term_Node_Tid_DepthList;
        private List<sodexoDistrict> districtList;
        private int maxPage;
        public int cardTypeIndex;
        public int districtIndex;

        private ObservableCollection<sodexoAffiliate> affiliates;
        public List<sodexoCardType> CardType
        {
            get
            {
                return term_Node_Tid_DepthList;
            }
        }
        public List<sodexoDistrict> Districts
        {
            get
            {
                return districtList;
            }
        }
        public ObservableCollection<sodexoAffiliate> Affiliates
        {
            get
            {
                return affiliates;
            }
        }
        public EventHandler<HtmlDocumentLoadCompleted> HomePageLoadedEvent
        {
            get
            {
                return HomePageLoaded;
            }
            set
            {
                HomePageLoaded = value;
            }
        }
        public EventHandler<HtmlDocumentLoadCompleted> SerchPageLoadedEvent
        {
            get
            {
                return SearchPageLoaded;
            }
            set
            {
                SearchPageLoaded = value;
            }
        }
        public int PageCount
        {
            get
            {
                return maxPage;
            }
        }
        public sodexoWebClient(string url,string serchUrl =@"http://www.club.cn.sodexo.com/affiliates/search?")
        {
            sodexoHomeUrl = url;
            sodexoSerchHomeUrl = serchUrl;
            HomePageLoaded = HomeSiteLoaded;
            SearchPageLoaded = SearchSiteLoaded;
            term_Node_Tid_DepthList = new List<sodexoCardType>();
            districtList = new List<sodexoDistrict>();
            affiliates = new ObservableCollection<sodexoAffiliate>();
            maxPage = 0;
        }
   
        private void openWebSite(string url,EventHandler<HtmlDocumentLoadCompleted> callBack)
        {
            HtmlWeb.LoadAsync(url, callBack);
        }
        
        public void HomeSiteLoaded(object sender, HtmlDocumentLoadCompleted args)
        {
            if (args.Error != null)
            {
                return;
            }
            initialTerm_Node_Tid_DepthList(args.Document);
        }
        public void SearchSiteLoaded(object sender, HtmlDocumentLoadCompleted args)
        {
            if (args.Error != null)
            {
                return;
            }
            getSearchResult(args.Document);
        }
        private void initialTerm_Node_Tid_DepthList(HtmlDocument doc)
        {
            HtmlNode node = doc.GetElementbyId("edit-term-node-tid-depth");
            foreach (HtmlNode childnode in node.ChildNodes)
            {
                if ((childnode.Attributes.Count == 0)||(childnode.Attributes.Count > 1))
                    continue;
                sodexoCardType tmpDepth = new sodexoCardType();

                tmpDepth.value = childnode.Attributes[0].Value;
                tmpDepth.text = childnode.NextSibling.InnerText;
                term_Node_Tid_DepthList.Add(tmpDepth);
            }

            HtmlNode districtNode = doc.GetElementbyId("edit-term-node-tid-depth-1");
            char[] delte_char = { '-' };
            foreach (HtmlNode childnode in districtNode.ChildNodes)
            {
                if ((childnode.Attributes.Count == 0) || (childnode.Attributes.Count > 1))
                    continue;
                sodexoDistrict tmpDepth = new sodexoDistrict();

                tmpDepth.Value = childnode.Attributes[0].Value;
              //  tmpDepth.Text = childnode.NextSibling.InnerText.TrimStart(delte_char);
                tmpDepth.Text = childnode.NextSibling.InnerText.Replace('-', '\t');
                districtList.Add(tmpDepth);
            }
        }

        private void getSearchResult(HtmlDocument doc)
        {
           HtmlNode tableNode =  doc.DocumentNode.SelectSingleNode("//table");
           HtmlNode tableBodyNode = tableNode.SelectSingleNode("tbody");
           HtmlNodeCollection tableRowNodes = tableBodyNode.SelectNodes("tr");

           foreach (HtmlNode trnode in tableRowNodes)
           {
               sodexoAffiliate affs = new sodexoAffiliate();
               try
               {
                   HtmlNode nameClumnNode = trnode.SelectSingleNode(@"td[@class='views-field views-field-title']");
                   HtmlNode linkNode = nameClumnNode.SelectSingleNode("a");
                   affs.Name = linkNode.InnerText;

                   HtmlNode addressClumnNode = trnode.SelectSingleNode(@"td[@class='views-field views-field-address']");
                   HtmlNode divNode = addressClumnNode.SelectSingleNode(@"div/div/div[@class='street-address']");
                   affs.Address = divNode.InnerText;

                   HtmlNode phoneClumnNode = trnode.SelectSingleNode(@"td[@class='views-field views-field-address-1']");
                   HtmlNode phoneNode = phoneClumnNode.SelectSingleNode(@"div/div/div[@class='phone']");
                   if (phoneNode.InnerText != "")
                       affs.PhoneNumber = phoneNode.InnerText.TrimStart(new char[3] { '电', '话', ':' });
                   else
                       affs.PhoneNumber = phoneNode.InnerText;
               }
               catch (Exception e)
               {
                   
               }
               affiliates.Add(affs);
           }

           HtmlNodeCollection lastPageNodes = doc.DocumentNode.SelectNodes(@"//li[@class='pager-last last']");
           if (lastPageNodes != null)
           {
               HtmlNode lastPageNode = lastPageNodes[0];
               HtmlNode lastPageLink = lastPageNode.ChildNodes["a"];
               string text = lastPageLink.Attributes["href"].Value;
               Regex re = new Regex(@"page=(\d*)");
               Match match = re.Match(text);
               string i = match.Result("$1");
               maxPage = Convert.ToInt32(i);
           }
        }

        public void init()
        {
            openWebSite(sodexoHomeUrl, HomePageLoaded);
        }

        private string generateSerchUrl(string cardTypeValue, string districtValue,int pageNumber = 0)
        {
            string serchUrl = sodexoSerchHomeUrl + "term_node_tid_depth=" + cardTypeValue + "&term_node_tid_depth_1=" + districtValue + "&page=" + pageNumber.ToString(); ;
            sodexoSerchUrl = serchUrl;
            return serchUrl;
        }

        public void getSerchWeb(string cardTypeValue, string districtValue, int pageNumber = 0)
        {
            generateSerchUrl(cardTypeValue, districtValue, pageNumber);
            openWebSite(sodexoSerchUrl, SearchPageLoaded);
        }
    }
}
